Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Encapsulation → Private Variables

Encapsulation

Private Variables

Private Variables in Python

In object-oriented programming (OOP), encapsulation is a crucial principle that bundles data (variables) and methods (functions) that operate on that data within a class. Encapsulation promotes data hiding and protects data integrity. While Python doesn't have strict "private" variables like some languages (e.g., Java's `private` keyword), it employs a naming convention to achieve a similar effect:

Name Mangling

Python uses name mangling to make instance variables less accessible from outside the class. This is achieved by prefixing the variable name with double underscores (`__`). For example, `__my_private_var` is considered a "private" variable.

How Name Mangling Works

When the interpreter encounters a double-underscore prefixed variable name, it automatically renames it to a more complex form, effectively hiding it from direct access outside the class. The renaming follows the pattern `_ClassName__variableName`. This makes it difficult (though not impossible) to access the variable directly from outside the class. Example 1: Basic Name Mangling
Basic Name Mangling class MyClass: def __init__(self, value): self.__private_var = value # Private variable def get_private_var(self): return self.__private_var def set_private_var(self, new_value): self.__private_var = new_value my_object = MyClass(10) print(my_object.get_private_var()) # Access using getter method: Output: 10 # Attempting direct access (will likely raise an AttributeError or return a mangled name) # print(my_object.__private_var) # This will likely result in an error or show the mangled name print(my_object._MyClass__private_var) #Accessing through mangled name. Avoid this! my_object.set_private_var(20) print(my_object.get_private_var()) # Access using setter method: Output: 20

Output

10 10 20
In this example, `__private_var` is considered "private." Direct access is discouraged, and the class provides `get_private_var` and `set_private_var` methods to interact with it safely. Note that accessing it via the mangled name is technically possible but should be avoided, as it breaks encapsulation and relies on implementation details.
Example 2: Inheritance and Name Mangling
Inheritance and Name Mangling class ParentClass: def __init__(self, value): self.__private_var = value class ChildClass(ParentClass): def access_private(self): # Attempting to access the parent's private variable print(self._ParentClass__private_var) my_child = ChildClass(5) my_child.access_private() # Output: 5 (still accessible via mangled name within subclass)

Output

5
Even in inheritance, the child class can access the parent's "private" variable through name mangling (using the mangled name). However, this is still considered bad practice; it breaks encapsulation and tightly couples the child class to the parent's internal implementation.
Example 3: Why Private is not truly Private
Understanding private variable class MyClass: def __init__(self, value): self.__private_var = value my_object = MyClass(100) print(dir(my_object)) # Shows all attributes of my_object, including the mangled name

Output

['_MyClass__private_var', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
The `dir()` function reveals all attributes of an object, including the mangled name of the "private" variable. This demonstrates that Python's "private" variables are not truly private; they are just less accessible, making accidental modification less likely.

Best Practices

Use name mangling judiciously: It's primarily meant for internal implementation details, not for strictly controlling external access. Overuse can make your code less readable. Favor getter and setter methods: These provide a controlled interface for accessing and modifying variables, enhancing code maintainability and preventing unexpected changes. Document your intention: Clearly state which attributes are intended to be internal-only in your class documentation. Consider using properties: Python's `@property` decorator offers a more elegant and Pythonic way to manage controlled access to attributes while still looking like direct attribute access. In essence, Python's approach to private variables emphasizes convention and readability rather than strict enforcement. While name mangling helps in achieving a level of data hiding, it's crucial to adopt best practices to maintain clean and robust object-oriented code.

Tutorials